<?php

namespace app\shop\controller\supplier;

use app\shop\controller\Controller;
use app\shop\model\supplier\ServiceSecurity as ServiceSecurityModel;

/**
 * 服务管理控制器
 */
class Security extends Controller
{
    /**
     * 获取列表
     */
    public function index()
    {
        // 列表
        $model    = new ServiceSecurityModel;
        $param    = $this->postData();
        $category = $model->getAll($param);
        // 数量
        $category_count = [
            'using'   => $model->getTotalByWhere(['audit_status' => 1]),
            'audit'   => $model->getTotalByWhere(['audit_status' => 0]),
            'no_pass' => $model->getTotalByWhere(['audit_status' => 2]),
        ];
        return $this->renderSuccess('', compact('category', 'category_count'));
    }

    /**
     * 添加
     */
    public function add()
    {
        $model = new ServiceSecurityModel;
        // 新增记录
        if ($model->add($this->postData())) {
            return $this->renderSuccess('添加成功');
        }
        return $this->renderError($model->getError() ?: '添加失败');
    }

    /**
     * 编辑
     */
    public function edit($service_security_id)
    {
        // 分类详情
        $model = ServiceSecurityModel::detail($service_security_id);
        // 更新记录
        if ($model->edit($this->postData())) {
            return $this->renderSuccess('更新成功');
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }

    /**
     * 删除
     */
    public function delete($service_security_id)
    {
        $model = ServiceSecurityModel::detail($service_security_id);
        if (!$model->remove()) {
            return $this->renderError('该服务使用中，删除失败');
        }
        return $this->renderSuccess('删除成功');
    }

    /**
     * 审核服务管理
     * @return \think\response\Json
     * @Author joey
     * @date 2024/3/27 10:55
     */
    public function audit()
    {
        $param = $this->postData();
        $model = new ServiceSecurityModel;

        if (!isset($param['service_security_id'])) {
            return $this->renderError('服务管理id不能为空');
        }
        $param['service_security_id'] = is_array($param['service_security_id']) ? $param['service_security_id'] : [$param['service_security_id']];
        $detail                       = $model->whereIn('service_security_id', $param['service_security_id'])->select();
        if ($detail->isEmpty()) {
            return $this->renderError('服务管理不存在');
        }
        $data = ['audit_status' => $param['audit_status'], 'remark' => $param['remark'] ?? ''];
        $num  = 0;
        foreach ($detail as $item) {
            $res = $item->allowField(['audit_status', 'remark'])->save($data);
            if ($res) {
                $num++;
            }
        }
        return $this->renderSuccess($num > 0 ? "审核成功{$num}条" : '审核失败');
    }
}